﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Microsoft Corporation" file="AdmAuthentication.cs">
//   Copyright © Microsoft Corporation.  All Rights Reserved.  
// This code released under the terms of the 
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
// </copyright>
// <summary>
//   Authentication helper for the Microsoft Translator on Azure.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Microsoft.MCSUK.RESXTranslator
{
    using System.Net;
    using System.Runtime.Serialization.Json;
    using System.Text;
    using System.Web;

    /// <summary>
    /// Authentication helper for the Microsoft Translator on Azure
    /// </summary>
    public class AdmAuthentication
    {
        /// <summary>
        /// Url for authentication in Microsoft Translator
        /// </summary>
        public static readonly string DatamarketAccessUri = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
        
        /// <summary>
        /// request string needed to request access token
        /// </summary>
        private readonly string request;

        /// <summary>
        /// Initializes a new instance of the <see cref="AdmAuthentication"/> class.
        /// </summary>
        /// <param name="clientId">The client id.</param>
        /// <param name="clientSecret">The client secret.</param>
        public AdmAuthentication(string clientId, string clientSecret)
        {
            // If clientid or client secret has special characters, encode before sending request
            this.request = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientId), HttpUtility.UrlEncode(clientSecret));
        }

        /// <summary>
        /// Requests the access token
        /// </summary>
        /// <returns>The access token</returns>
        public AdmAccessToken GetAccessToken()
        {
            return HttpPost(DatamarketAccessUri, this.request);
        }

        /// <summary>
        /// Helper method to formulate the proper request
        /// </summary>
        /// <param name="datamarketAccessUri">Web Address for the request</param>
        /// <param name="requestDetails">request details</param>
        /// <returns>The access toen</returns>
        private static AdmAccessToken HttpPost(string datamarketAccessUri, string requestDetails)
        {
            // Prepare OAuth request 
            var webRequest = WebRequest.Create(datamarketAccessUri);
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method = "POST";
            var bytes = Encoding.ASCII.GetBytes(requestDetails);
            webRequest.ContentLength = bytes.Length;
            using (var outputStream = webRequest.GetRequestStream())
            {
                outputStream.Write(bytes, 0, bytes.Length);
            }

            using (var webResponse = webRequest.GetResponse())
            {
                var serializer = new DataContractJsonSerializer(typeof(AdmAccessToken));

                // Get deserialized object from JSON stream
                var token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());
                return token;
            }
        }
    }    
}
